package com.demo.sender.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class AttachmentValidator {

  private static final List<String> FORBIDDEN_TYPES = List.of(
      "application/x-msdownload",
      "application/x-msdos-program",
      "application/bat",
      "application/x-bat"
  );

  private static final List<String> ALLOWED_TYPES = List.of(
      "application/pdf",
      "image/jpeg",
      "image/png",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  );

  public void validateFile(MultipartFile file) {
    // 1. 文件大小验证
    if (file.getSize() > 40 * 1024 * 1024) {
      throw new RuntimeException("文件大小超过限制: " + file.getOriginalFilename());
    }
    // 2. 内容类型验证
    String contentType = file.getContentType();
    if (contentType == null) {
      throw new RuntimeException("无法识别文件类型: " + file.getOriginalFilename());
    }
    if (FORBIDDEN_TYPES.stream().anyMatch(contentType::contains)) {
      throw new RuntimeException("禁止的文件类型: " + file.getOriginalFilename());
    }
    if (!ALLOWED_TYPES.contains(contentType)) {
      throw new RuntimeException("不支持的文件类型: " + file.getOriginalFilename());
    }
    // 3. 文件名验证
    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.contains("..") || fileName.contains("/"))) {
      throw new RuntimeException("无效的文件名: " + fileName);
    }
    // 4. 内容嗅探验证
    try {
      byte[] content = file.getBytes();
      if (isExecutable(content)) {
        throw new RuntimeException("可疑的可执行文件: " + fileName);
      }
    } catch (IOException e) {
      log.error("文件内容验证失败", e);
    }
  }

  private boolean isExecutable(byte[] content) {
    // 简化的可执行文件检测
    return content.length > 4 &&
        content[0] == 0x4D && content[1] == 0x5A; // MZ header
  }


}